import React, { useState, useEffect } from "react";
import { url } from "../../services";
import {
  Button,
  Modal,
  Form,
  Input,
  Upload,
  message,
  Select,
  Image,
} from "antd";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import { addShops } from "../../services/shops";
import { findAll } from "../../services/type";
// import { addUpload} from "../../services/shops";
import ImgCrop from "antd-img-crop";
const { Option } = Select;

export default function Add({ show, shop }) {
  // 对话框是否可见
  const [isModalVisible, setIsModalVisible] = useState(false);

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const [form] = Form.useForm(); //钩子函数绑定from表单
  const [fileList, setFileList] = useState([]);

  // 分类
  const [shopType, setShopType] = useState([]);
  const children = [];
//   shop.map((item) =>
//     children.push(<Option key={item._id} value={item._id}>{item.typeName}</Option>)
//   );

  for (let i = 0; i < shopType.length; i++) {
    children.push(<Option key={shopType[i]._id} value={shopType[i]._id}>{shopType[i].typeName}</Option>);
  }
  // 增加按钮
  const showModal = async () => {
    setIsModalVisible(true);
    let data = await findAll();
    console.log(data.data, "type");
    // let typeData = data.data.map((item, i) => item.typeName);
    // console.log(typeData, "typeData");
    setShopType(data.data);
  };
   // 修改图片的格式
  //  const getBase64 = (img, callback) => {
  //   const reader = new FileReader();
  //   reader.addEventListener("load", () => callback(reader.result));
  //   reader.readAsDataURL(img);
  // };
  const getBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => resolve(reader.result);

    reader.onerror = (error) => reject(error);
  });
  // 上传图片
// 
  const onChange = ({ fileList: newFileList }) => {
    // console.log(info,'增加');
    setFileList(newFileList);
  };
//   const onChange = (file) => {
//     console.log(file,'file');
//   if (file.fileList.length > 0) {
//     file.fileList.map(async(item) => {
//       let aaa = await getBase64(item.originFileObj);
//       console.log(aaa,'aaa');
//       setFileList(aaa)
//     })
  
//   }
// }

  const onPreview = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  // 是否上架
  const handleUp = (value) => {
    // show(value);
    console.log(value.value);
  };
  //下拉框
  const handleType = (value) => {
    console.log(value.value);
    console.log(`selected ${value.value}`);
  };
  // 点击确认
  const handleOk = async () => {
    let values = form.getFieldValue();
    console.log(values, "所有值");

    let data = await addShops({
      ...values,
      types: values.typeName.value,
      isStatus:values.isStatus.label,
      shopImg: values.shopImg.fileList.map((item)=>item.response.filename),
    });
    console.log(data, "zengjia");
    show();
    setIsModalVisible(false);
  };
  // 点击取消
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <div>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={showModal}
        style={{ width: "80px", height: "30px" }}
      >
        增加
      </Button>
      <Modal
        title="增加商品"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form
          name="addForm"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          form={form}
        >
          <Form.Item label="商品名" name="name">
            <Input />
          </Form.Item>

          <Form.Item label="分类名" name="typeName">
            <Select labelInValue onChange={handleType}>
              {shopType.map((item, i) =>(
                <Option key={item} value={item._id}>{item.typeName}</Option>
              ))}
              {/* {children} */}
            </Select>
          </Form.Item>

          <Form.Item name="price" label="价格">
            <Input />
          </Form.Item>
          <Form.Item name="total" label="数量">
            <Input />
          </Form.Item>

          <Form.Item name="isStatus" label="是否上架">
            <Select
              labelInValue
              defaultValue='hit'
              // defaultValue='hit'
              style={{ width: 120 }}
              onChange={handleUp}
            >
              <Option value="hit">已上架</Option>
              <Option value="down">已下架</Option>
            </Select>
          </Form.Item>
          <Form.Item label="商品图片" name="shopImg">
            <Upload
              name="file"
              action={url + "/upload"}
              listType="picture-card"
              fileList={fileList}
              onChange={onChange}
              onPreview={onPreview}
            >
              {fileList.length < 7 && "+ Upload"}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
  // };
}
